package com.gsy.springbootshiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: springboot-shiro
 * @description:
 * @author: GSY
 * @create: 2020-03-16 14:30
 **/

@Configuration
public class ShiroConfig {




    @Bean
      public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){

          ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
          //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        /**
         * onon:   无须权限就可以访问
         * authc:  必须认证才可以访问
         * user: 必须拥有记住我功能才可以访问
         * perms: 拥有对某个资源的权限才可以访问
         * role:拥有某个角色权限才能访问
         */

          Map<String ,String> filtermap = new LinkedHashMap<>();
         /* filtermap.put("/user/add","authc");
          filtermap.put("/user/update","authc");*/
         //使用通配符

        //授权，正常情况下，没有授权会跳转到未授权页面
        filtermap.put("/user/add","perms[user:add]");
        filtermap.put("/user/update","perms[user:update]");
        //登录拦截
          filtermap.put("/user/*","authc");
          shiroFilterFactoryBean.setFilterChainDefinitionMap(filtermap);
          //设置登录的请求
          shiroFilterFactoryBean.setLoginUrl("/tologin");

          //未授权页面
          shiroFilterFactoryBean.setUnauthorizedUrl("/unauthor");
          return shiroFilterFactoryBean;
      }



         @Bean
          public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getUserRealm")UserRealm userRealm){
              DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
              //关联Realm
              securityManager.setRealm(userRealm);
              return securityManager;
          }


          //创建Realm 对象，需要自定义类
          @Bean
         public UserRealm getUserRealm(){
           return new UserRealm();
       }


       //整合shiroDialect :用来整合 shiro thymeleaf
        @Bean
        public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
        }

}
